package com.jaiai.work.user.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jaiai.work.user.entity.TUser;
import com.jaiai.work.user.service.ITUserService;
import com.jaiai.work.util.IdGenerate;
import com.jaiai.work.util.IdWorkUtil;
import com.jaiai.work.util.MD5;
import com.jaiai.work.util.RestResultGenerator;
import com.jaiai.work.util.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.rmi.rmic.iiop.IDLGenerator;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 佳爱网络科技
 * @since 2018-04-20
 */
@RestController
@RequestMapping("/api/v1/app/user")
public class TUserController {
    private  static  final Logger log= LoggerFactory.getLogger(TUserController.class);

    @Autowired
    private ITUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IdWorkUtil idWorkUtil;

    /**
     * 登录
     * @param email
     * @param passowrd
     * @param platform
     * @return
     */
    @PostMapping("/login")
    public  Object login(String email,String passowrd,Integer platform){
        TUser user=userService.selectOne(new EntityWrapper().eq("email",email));
        if(user==null){
            return RestResultGenerator.genErrorResult("用户不存在");
        }
        if(!MD5.MD5Encode(passowrd).equals(user.getPassword())){
            return RestResultGenerator.genErrorResult("密码错误");
        }
        String token=IdGenerate.getUUID();
        redisUtil.hashSet(0,"token",user.getUId(), token);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return  RestResultGenerator.genSuccessResult(map);
    }


    /**
     * 用户注册并且返回token
     * @param user
     * @return
     */
    @PostMapping("/register")
    public  Object register(@RequestBody TUser user){
        user.setCreateTime(new Date());
        user.setLastLoginTime(new Date());
        try {
            user.setUId(idWorkUtil.generateId("project_userId",4));
         }catch (Exception e){
            log.error("id 生成失败 error:"+e.getMessage());
            return RestResultGenerator.genErrorResult("服务器异常");
        }
        try {
            user.setPassword(MD5.MD5Encode(user.getPassword()));
            userService.insert(user);
        }catch (Exception e){
            log.error("注册失败 error:"+e.getMessage());
            return RestResultGenerator.genErrorResult("服务器异常");
        }
        String token=IdGenerate.getUUID();
        redisUtil.hashSet(0,"token",user.getUId(), token);
        Map<String,Object> map=new HashMap<>();
        map.put("token",token);
        map.put("user",user);
        return  RestResultGenerator.genSuccessResult(map);
    }
}
